<?php

namespace App\Model;

use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\DbManager;
use Trois\Lib\HandleMessage;

class BaseModel extends AbstractModel
{
    use HandleMessage;

    protected string $primaryKey;

    /**
     * 批量更新数据
     * 只能通过主键更新，
     * $datas = [
     *   ['id'=>1,'name'=>'11','age'=>3],
     *   ['id'=>2,'name'=>'22','age'=>4],
     *   ['id'=>3,'name'=>'33','age'=>5],
     * ]
     * @param $datas
     */
    public function batchUpdate(array $datas): void
    {
        $builder = new QueryBuilder();

        $sql = "";
        $sqlField = [];
        $ids = [];

        $primaryKey = $this->schemaInfo()->getPkFiledName();

        foreach ($datas as $data) {

            foreach ($data as $key => $value) {

                if ($primaryKey === $key) {
                    $ids[] = $value;
                } else {

                    if (isset($sqlField[$key])) {
                        $sqlField[$key] .= sprintf(" WHEN %u THEN '%s'", $data[$primaryKey], $value);
                    } else {
                        $sqlField[$key] = sprintf(" WHEN %u THEN '%s'", $data[$primaryKey], $value);
                    }

                }

            }

        }

        foreach ($sqlField as $uField => $uValue) {
            $sql .= $uField . " = CASE " . $primaryKey . $uValue . " END,";
        }

        $sql = rtrim($sql, ',');

        $sql .= " WHERE " . $primaryKey . " in (" . implode(',', $ids) . ")";

        $sql = "UPDATE " . $this->getTableName() . " SET " . $sql;

        DbManager::getInstance()->query($builder->raw($sql), true);

    }

    /**
     * 批量插入数据
     * $datas = [
     *   ['name'=>'11','age'=>3],
     *   ['name'=>'22','age'=>4],
     *   ['name'=>'33','age'=>5],
     * ]
     * @param $datas
     */
    public function batchAdd($datas): void
    {
        $builder = new QueryBuilder();

        $values = [];
        foreach ($datas as $data) {
            $_data = [];

            foreach ($data as $_d) {
                $_data[] = "\"$_d\"";
            }

            $values[] = "(" . implode(',', array_values($_data)) . ")";
        }

        $sql = "insert into " . $this->getTableName() . " (" . implode(',', array_keys(current($datas))) . ") values " . implode(',', $values);

        DbManager::getInstance()->query($builder->raw($sql), true);

    }


}